<template>
  <el-drawer v-model="visible" title="编辑区域">
    <el-form label-position="top" ref="formRef" :model="modelValue" :rules="rules">
      <el-form-item label="父级区域" prop="parent.id" v-if="!hide">
        <el-tree-select
          style="width: 100%"
          v-model="modelValue.parent!.id"
          check-strictly
          node-key="id"
          clearable
          :load="lazyFetchTrees"
          :multiple="false"
          lazy
          :props="{
            label: 'name'
          }"
          :render-after-expand="false"
          check-on-click-node
          @node-click="changeArea"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="父级区域编码" prop="pCode">
        <el-input disabled v-model="modelValue.pCode"></el-input>
      </el-form-item>
      <el-form-item label="区域名称" prop="name">
        <el-input v-model="modelValue.name"></el-input>
      </el-form-item>
      <el-form-item label="区域编码" prop="code">
        <el-input v-model="modelValue.code"></el-input>
      </el-form-item>
      <el-form-item label="区域层级" prop="level">
        <el-input disabled v-model="modelValue.level"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { editArea, fetchAreaInfo, fetchByParent, saveArea } from "@/api/modules/area";
import { ResultEnum } from "@/enums/httpEnum";
import { AreaSchema } from "@/schema";
import { ElMessage, FormInstance } from "element-plus";
import { computed, nextTick, reactive, ref, watch } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { EmitProps } from "@/typings/interface";
import { isNotEmpty } from "@/utils/isHelper";

const visible = ref<boolean>(false);
const modelValue = reactive<AreaSchema>({
  code: "",
  name: "",
  level: 0,
  pCode: "0",
  parent: { id: "" } as AreaSchema
});

const hide = computed(() => {
  return isNotEmpty(modelValue.id);
});

const rules = {
  code: [{ required: true, message: "请输入区域编码", trigger: "blur" }],
  name: [{ required: true, message: "请输入区域名称", trigger: "blur" }]
};

const formRef = ref<FormInstance>();
interface Tree extends AreaSchema {
  children?: Tree[];
}

function lazyFetchTrees(node: Node, resolve: (data: Tree[]) => void, reject: () => void) {
  const { data } = node;
  fetchByParent(data).then(r => {
    const { data, message, code } = r;
    if (code === ResultEnum.SUCCESS) {
      resolve(data ?? []);
    } else {
      ElMessage.error(message);
      reject();
    }
  });
}

function changeArea(area) {
  const { level, code } = area;
  modelValue.pCode = code;
  modelValue.level = level + 1;
  console.log(modelValue);
}

const emits = defineEmits<EmitProps>();

function submit() {
  formRef.value?.validate().then(valid => {
    if (valid) {
      if (modelValue.id) {
        edit();
      } else {
        save();
      }
    }
  });
}

function edit() {
  editArea({ id: modelValue.id }, modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      visible.value = false;
      emits("success");
    } else {
      ElMessage.error(message);
    }
  });
}

function save() {
  saveArea(modelValue).then(r => {
    const { code, message } = r;
    if (code === ResultEnum.SUCCESS) {
      visible.value = false;
      emits("success");
    } else {
      ElMessage.error(message);
    }
  });
}

defineExpose({
  open(row?: AreaSchema) {
    visible.value = true;
    if (row?.id) {
      fetchAreaInfo({ id: row.id }).then(r => {
        const { code, data, message } = r;
        if (code === ResultEnum.SUCCESS) {
          nextTick(() =>
            Object.assign(modelValue, data, {
              parent: isNotEmpty(data.parent) ? data.parent : { id: "" }
            })
          );
        } else {
          ElMessage.error(message);
        }
      });
    }
  }
});

watch(
  () => visible.value,
  newVal => {
    if (!newVal) {
      formRef.value?.resetFields();
      modelValue.id = "";
      modelValue.parent = { id: "" } as AreaSchema;
    }
  }
);
</script>
